<?php
/**
 * Created by PhpStorm.
 * User: HS032
 * Date: 2020/8/21
 * Time: 13:52
 */

namespace ticket\modules\backend\controllers;

use ticket\libs\Tools;
use ticket\modules\backend\models\CommonApp;
use ticket\modules\backend\models\Syslog;
use Yii;
use yii\log\FileTarget;
use yii\web\Controller;

class BasicController extends Controller
{
    protected $userInfo;//
    protected $appId;
    protected $permissions;//角色权限信息
    protected $permissionApps;

    public function init()
    {
        parent::init();
        /*请求认证中心,获取用户登录信息*/
//        $this->userInfo = [
//            'admin_id' =>1,
//            'username' =>'jiang',
//            'comid' =>00000000,
//            'role_id' =>0,
//            'avatar' =>'default_colleagues.jpg',
//            'identity' =>0,
//            'add_time' =>'2019-05-22 16:43:40',
//            'com_id' => 0,
//            'issuper' => 1
//        ];

        if(isset(Yii::$app->session->get('loginInfo')->userInfo)){
            $this->userInfo = Yii::$app->session->get('loginInfo')->userInfo;
            $this->permissions = Yii::$app->session->get('loginInfo')->permissions;
            $this->permissionApps = Yii::$app->session->get('loginInfo')->permissionApps;
        };

    }

    public function beforeAction($action)
    {

        $origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
        $allow_origin = array(
            'http://10.9.87.155:8080',
            'http://127.0.0.1:8080',
            'http://localhost:8080',
            'http://view.horsevision.cn',
            'http://view.raysfly.com',
            'http://yun.horsevision.cn',
            'http://cloud.raysfly.com',
            'http://yun.raysfly.com',
        );

        // P($origin);
        if(in_array($origin, $allow_origin) || !empty($origin)){
            header('Access-Control-Allow-Origin:'.$origin);
            header("Access-Control-Request-Headers: Origin, X-Requested-With, Content-Type, Accept,Authorization");
            header('Access-Control-Allow-Headers:Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With, Authorization');
            header('Access-Control-Allow-Methods:POST,GET,OPTIONS');
            header('Access-Control-Allow-Credentials:true');
        }

        $module = $this->module->id;
        $controller = $this->id;
        $action = $this->action->id;
        $router = $module . '=' . $controller . '=' . $action;


        $headerData = Yii::$app->request->getHeaders();
        if (!empty($headerData['Authorization'])){
            $res = $this->getAppId($headerData['Authorization']);
        }


        if (parent::beforeAction($action)) {
            if(!empty($this->userInfo)){

                // return true;

                /*验证权限*/
                $pass = false;
                if($this->userInfo['issuper'] == 1 or
                    in_array($router, Yii::$app->params['allowRouter'])){//菜单列表
                    $pass = true;
                }else{
                    foreach($this->permissions as $k => $v){
                        if(isset($this->get['appid'])){
                            if($v['appid'] == $this->get['appid'] and $v['m'] == $module and $v['c'] == $controller and $v['a'] == $action){
                                $pass = true;
                                break;
                            }
                        }else{
                            // echo $v['m'] . '*' . $v['c'] . '*' . $v['a'] . '<br>';
                            // echo $module . '-' . $controller . '-' . $action . '<br>';
                            // echo '----------------<br>';
                            if($v['m'] == $module and $v['c'] == $controller and $v['a'] == $action){
                                $pass = true;
                                break;
                            }
                        }
                    }
                }
                if($pass){
                    return true;
                }else{
                    echo Tools::showRes(10020,'您没有权限');
                    return false;
                }


            };
            if(!isset($errno)){
                echo Tools::showRes(10020,'您没有权限');
                return false;
            }
        }

    }


    public function actionOpenApp()
    {
        if (\Yii::$app->request->isPost){
            $post = \Yii::$app->request->post();
            $appCommentModel = new CommonApp();
            $this->recordLogin(10001,'开通APP实例成功',json_encode($post,JSON_UNESCAPED_UNICODE));

            if(($appInfo = $appCommentModel->addApp($post)) !== false){
                $backInfo = [0, '开通APP实例成功'];//返回信息
                //开通直播间
//                Live::add(time(),$post['app_name'],$appInfo['appid']);
                $this->recordLogin(10001,'开通APP实例成功',json_encode($appInfo));
                return $this->showRes($backInfo,['appinfo' => $appInfo]);
            }
        }
        return $this->showRes([0, '开通APP实例失败']);

        //http://paycentre.horsevision.cn/index.php?r=

    }


    protected function setSysLog($content)
    {
        $userInfo = Yii::$app->session->get('loginInfo')->userInfo;
        $patams = [
            'SysLog' => [
                'user_id' => isset($userInfo['admin_id'])?$userInfo['admin_id']:1,
                'username' => isset($userInfo['username'])?$userInfo['username']:'admin',
                'login_add' => '',
                'login_ip' => Yii::$app->request->userIP,
                'content' => $content,
                'operate_time' => date("Y-m-d H:i:s"),
            ]
        ];
//        var_dump($patams);die;
        $sysModel = new Syslog();
        if ($sysModel->addInfo($patams)){
            return true;
        }else{
            return false;
        }
    }



    protected function getAppId($appId)
    {
        $appModel = new CommonApp();
        $app_id = $appModel->getAppId($appId);
        $this->appId = $app_id;
        return true;
    }



    /*
    返回客户端函数
    $args = array(
        '0'  返回码
        '1'  返回信息
    )
    $data  返回数据，一般为数组，比如获取信息列表信息的时候
    $url   返回链接，跳转链接，比如微信登录的时候
    */
    public static function showRes($args = [0, '操作成功'], $data = '', $url = '')
    {
        $res = array(
            'code' => $args[0],
            'info' => $args[1]
        );
        if(!empty($data)){
            $res['data'] = $data;
        }

        if(!empty($url)){
            $res['url'] = $url;
        }
         return json_encode($res, JSON_UNESCAPED_UNICODE);
//        return $res;//JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES = 320  中文/ 同时生效
    }


    protected function recordLogin($code,$msg,$data)
    {
        $log = new FileTarget();
        $log->logFile = Yii::$app->getRuntimePath() . '/logs/send_' . date('Ymd') . '.log';
        $log->messages[] = [
            "[url:{$_SERVER['REQUEST_URI']}],[data:{$code},{$msg},{$data}]",
            1,
            'application',
            time(),
        ];
        $log->export();
    }

}